package org.my.stock.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyUtil {

//    public static Connection getConnection() throws PropertyVetoException, SQLException {
//        ComboPooledDataSource dataSource = new ComboPooledDataSource();
//        dataSource.setDriverClass("org.h2.Driver");
//        dataSource.setJdbcUrl("jdbc:h2:~/data;AUTO_SERVER=TRUE");
//        dataSource.setUser("root");
//        dataSource.setPassword("root");
//
//        // 初始化连接池容量
//        dataSource.setInitialPoolSize(10);
//        // 设置连接池最大容量
//        dataSource.setMaxPoolSize(20);
//        // 设置连接池不足时，每次向数据库申请的连接数量
//        dataSource.setAcquireIncrement(2);
//        // 设置剩余多少连接数时，开始申请新连接
//        dataSource.setMinPoolSize(2);
//
//        return dataSource.getConnection();
//    }

    private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);

    // Date → String
    public static String dateToString(Date date) {
        return sdf.format(date);
    }

    // String → Date
    public static Date stringToDate(String dateStr) throws ParseException {
        return sdf.parse(dateStr);
    }

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:~/data;AUTO_SERVER=TRUE", "root", "root");

        return conn;
    }

    public static java.sql.Date toDate(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            java.sql.Date sqlDate = new java.sql.Date(format.parse(dateStr).getTime());
            return sqlDate;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void execute(String sql) throws SQLException, ClassNotFoundException, PropertyVetoException {
        PreparedStatement st = getConnection().prepareStatement(sql);
        st.executeUpdate();

        st.close();
    }

    public static ResultSet query(String sql) throws SQLException, ClassNotFoundException, PropertyVetoException {
        PreparedStatement stmt = null;
        stmt = getConnection().prepareStatement(sql);

        // 5. 执行查询并获取结果集
        ResultSet rs = stmt.executeQuery();

        return rs;
    }

    public static Gson getGson()
    {
        return new GsonBuilder()
                .enableComplexMapKeySerialization()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }
}








































